package com.atguigu.gmall.mq.receiver;

import com.atguigu.gmall.mq.config.DelayedMqConfig;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class DelayedReceiver {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 延迟插件消费者
     *
     * 问题：消息在失败重试时，发送了多次，消费者重复消费
     *     幂等性
     *  解决：
     *       redis -setnx
     *
     * @param msg
     * @param message
     * @param channel
     */
    @RabbitListener(queues = DelayedMqConfig.queue_delay_1)
    @SneakyThrows
    public void delayProcess(String msg, Message message, Channel channel){

        //设置执行的标记
        Boolean result = redisTemplate.opsForValue().setIfAbsent(msg, "0", 10, TimeUnit.MINUTES);
        //判断
        if(result){

            //时间格式化对象
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            System.out.println("收到消息的时间为："+format.format(new Date()));

            System.out.println("收到的消息：\t"+msg);

            //表示消息消费了
            redisTemplate.opsForValue().set(msg,"1",10, TimeUnit.MINUTES);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);

        }else{

            //获取执行状态
            String flag = (String) redisTemplate.opsForValue().get(msg);
            //判断
            if("1".equals(flag)){


                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }else{

                //时间格式化对象
                SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println("收到消息的时间为："+format.format(new Date()));

                System.out.println("收到的消息：\t"+msg);

                //表示消息消费了
                redisTemplate.opsForValue().set(msg,"1",10, TimeUnit.MINUTES);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            }



        }




    }
}
